package org.pitest.ant;

import org.apache.tools.ant.types.FileSet;
import org.pitest.ant.util.ClassUtils;
import org.pitest.ant.util.FileSetUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author Aidan Morgan
 */
public class TargetTests {
  private static Logger s_log = Logger.getLogger(TargetTests.class.getName());

  private PitestAntTask task;

  private List<FileSet> targetTests;
  private List<Filter> filters;

  public TargetTests(PitestAntTask task) {
    this.task = task;
    this.targetTests = new ArrayList<FileSet>();
    this.filters = new ArrayList<Filter>();
  }

  public List<FileSet> getTargetTests() {
    return Collections.unmodifiableList(targetTests);
  }

  public List<Filter> getFilters() {
    return filters;
  }

  public FileSet createFileSet() {
    FileSet tc = new FileSet();
    targetTests.add(tc);

    return tc;
  }

  public Filter createFilter() {
    Filter f = new Filter(task);
    filters.add(f);

    return f;
  }


  public String asString(String seperator) {
    StringBuffer buff = new StringBuffer();
    String sep = "";

    for (String s : asList()) {
      buff.append(sep);
      buff.append(s);

      sep = seperator;
    }

    return buff.toString();
  }

  public List<String> asList() {
    List<String> result = new ArrayList<String>();

    for (final FileSet tc : getTargetTests()) {
      List<File> files = FileSetUtils.convertFileSet(tc);

      for (File f : files) {
        try {
          result.add(ClassUtils.getClassName(f));
        } catch (IllegalArgumentException e) {
          s_log.warning("Could not load classname for file " + f.getAbsolutePath() + ".");
        }
      }
    }

    for (Filter f : getFilters()) {
      result.add(f.getFilter());
    }

    return result;
  }

  public int size() {
    return asList().size();
  }

}
